package grouper;

import database.table.DBTableData;

public abstract class Grouper {
	protected DBTableData		data;
	
	public Grouper( DBTableData data ) {
		this.data = data;
	}
	
	public int propagate( int refRow, String colName ) {
		int gcol = data.getColumnIndex("Group");
		int vcol = data.getColumnIndex(colName);
		
		if (gcol == -1) {
			System.out.println("ERROR: table not grouped, cannot propagate");
			return 0;
		}
		else if (vcol == -1) {
			System.out.println("ERROR: column " + colName + " doest not exist");
			return 0;
		}
		
		int gid = (Integer) data.getValueAt(refRow, gcol);
		String value = (String) data.getValueAt(refRow, vcol);
		int changed = 0;
		
		for (int row = 0; row < data.getRowCount(); row++) {
			if (data.getValueAt(row, "Group").equals(gid)) {
				data.setValueAt(value, row, vcol);
				changed++;
			}
		}
		
		return changed;
	}
	
	public void propagateAll( String colName ) {
		int gcol = data.getColumnIndex("Group");
		int vcol = data.getColumnIndex(colName);
		
		if (gcol == -1) {
			System.out.println("ERROR: table not grouped, cannot propagate");
			return;
		}
		else if (vcol == -1) {
			System.out.println("ERROR: column " + colName + " doest not exist");
			return;
		}
		
		int refRow = -1;
		int curGroup = -1;
		int nextGroup;
		String curValue = "-";
		
		for (int row = 0; row < data.getRowCount(); row++) {
			nextGroup = (Integer) data.getValueAt(row, gcol);
			if (refRow == -1 || nextGroup != curGroup) {
				curValue = (String) data.getValueAt(row, vcol);
				if (curValue.length() > 0) {
					refRow = row;
					curGroup = nextGroup;
					
					for (int back = row - 1; back >= 0 && data.getValueAt(back, gcol).equals(curGroup); back--) {
						data.setValueAt(curValue, back, vcol);
					}
				}
				else
					refRow = -1;
			}
			else {
				data.setValueAt(curValue, row, vcol);
			}
		}
		
		data.fireTableStructureChanged();
	}
	
	public abstract void group();
}
